import sys
import os
import io
import configparser
import logging

# 添加本地库路径
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib')))

# 在 Web 框架（如 Flask）中使用
from flask import Flask, request, send_file
# generate_pdf.py

from flask_cors import CORS

# 导入 PDFPlaceholderReplacer 类
from PDFPlaceholderReplacer import PDFPlaceholderReplacer

# 配置日志记录器
logging.basicConfig(level=logging.INFO,  # 设置日志级别
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # 设置日志格式
                    datefmt='%Y-%m-%d %H:%M:%S')  # 设置日期和时间格式
 
# 获取一个日志记录器对象（通常使用__name__来获取当前模块的名称作为日志器的名称）
logger = logging.getLogger(__name__)
 
app = Flask(__name__)
# 解决跨域问题
CORS(app) 

def load_server_config():
    """加载服务器配置"""
    config = configparser.ConfigParser()
    config.read(os.path.join(os.path.dirname(__file__), 'web.ini'))
    return {
        'host': config.get('web', 'host', fallback='127.0.0.1'),
        'port': config.getint('web', 'port', fallback=5000),
        'debug': config.getboolean('web','debug', fallback=False)
    }


processor = PDFPlaceholderReplacer()

@app.route('/generate-pdf', methods=['POST'])
def generate_pdf():
    # 获取请求参数
    #template_bytes = request.files['template'].read()
    requestJson = request.json
    logger.info(f"请求报文 {requestJson} 接收成功")
    
    # 提取并读取源文件
    source_path = requestJson.get('templateFilePath')
    outFilePath = requestJson.get('outFilePath')
    if source_path:
        try:
            # 需要以二进制方式读取，不能以with open('file.txt', 'r', encoding='utf-8') as file:这种文本方式读取
            with open(source_path, 'rb') as file:
                source_content = file.read()
                # 后续处理逻辑
        except FileNotFoundError:
            return "文件路径不存在", 400
        except PermissionError:
            return "无权限访问文件", 403
    else:
        return "未提供有效文件路径", 400
        
    jsonparam=requestJson.get('jsonparam',{})
    # 处理 PDF
    output_bytes = processor.process_pdf(source_content, jsonparam)
    
    processor.savePdf(outFilePath,output_bytes)
    # 返回文件
    return outFilePath

@app.after_request
def add_security_headers(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    return response

if __name__ == '__main__':
    try:
        server_config = load_server_config()
        print(f"启动服务：{server_config['host']}:{server_config['port']}:{server_config['debug']}")
        app.run(
            host=server_config['host'],
            port=server_config['port'],
            debug=server_config['debug']
        )
    except Exception as e:
        print(f"Error: {e}")